package com.sjx.lib_base.manager

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import androidx.annotation.RequiresApi
import androidx.core.content.ContextCompat
import com.yanzhenjie.permission.AndPermission
import com.yanzhenjie.permission.Action

/**
 * FileName: PermissionsManager
 * Founder: sjx
 * Profile: 权限管理类
 */
object PermissionsManager {

    val codeWindowRequest = 100

    val permissionLocationAndStorage = arrayOf(
        Manifest.permission.ACCESS_FINE_LOCATION,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
    )

    /**
     * 检查窗口权限
     */
    fun checkWindowPermission(context: Context): Boolean {
        return Settings.canDrawOverlays(context)
    }

    fun requestWindowPermission(activity: Activity, packageName: String) {
        activity.startActivityForResult(
            Intent(
                Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                Uri.parse("package:$packageName")
            ), codeWindowRequest
        )
    }

    //检查权限
    fun checkPermission(context: Context, permission: String): Boolean {
        return ContextCompat.checkSelfPermission(
            context,
            permission
        ) == PackageManager.PERMISSION_GRANTED
    }

    //检查多个权限
    fun checkPermission(context: Context, permission: Array<String>): Boolean {
        permission.forEach {
            if (ContextCompat.checkSelfPermission(
                    context,
                    it
                ) == PackageManager.PERMISSION_DENIED
            ) {
                return false
            }
        }
        return true
    }

    //请求权限
    fun requestPermission(
        context: Context,
        permission: Array<String>,
        granted: Action<List<String>>
    ) {
        AndPermission.with(context)
            .runtime()
            .permission(permission)
            .onGranted(granted)
            .start()
    }

}